<?php

namespace Eccang\OpenApi\Utils;


class Sign
{
    /**
     * 加密
     * @param $data
     * @param $key
     * @param string $method
     * @param null $iv
     * @return string
     */
    public static function encrypt($data, $key, $method = 'AES-128-CBC', $iv = null)
    {
        if (empty($iv)) {
            $iv = $key;
        }
        $iv = self::ivSbustr($iv);

        return openssl_encrypt(self::addPkcs7Padding($data), $method, $key, 0, $iv);
    }

    /**
     * 解密
     * @param $data
     * @param $key
     * @param string $method
     * @param null $iv
     * @return String
     */
    public static function decrypt($data, $key, $method = 'AES-128-CBC', $iv = null)
    {
        if (empty($iv)) {
            $iv = $key;
        }
        $iv = self::ivSbustr($iv);
        return self::stripPkcs7Padding(openssl_decrypt($data, $method, $key, 0, $iv));
    }

    /**
     * pkcs7补码
     * @param string $string 明文
     * @param int $blocksize Blocksize , 以 byte 为单位
     * @return String
     */
    protected static function addPkcs7Padding($string, $blocksize = 16)
    {
        //不补码了
        return $string;

        $len = strlen($string); //取得字符串长度
        $pad = $blocksize - ($len % $blocksize); //取得补码的长度
        $string .= str_repeat(chr($pad), $pad); //用ASCII码为补码长度的字符， 补足最后一段
        return $string;
    }

    /**
     * 除去pkcs7 补码
     * @param String 解密后的结果
     * @return String
     */
    protected static function stripPkcs7Padding($string)
    {
        //不补码了
        return $string;
        if (empty($string)) {
            return false;
        }
        $slast = ord(substr($string, -1));
        $slastc = chr($slast);

        if (preg_match("/$slastc{" . $slast . "}/", $string)) {
            $string = substr($string, 0, strlen($string) - $slast);
            return $string;
        } else {
            return false;
        }
    }

    protected static function ivSbustr($iv, $length = 16)
    {
        return substr($iv, 0, $length);
    }
}
